package com.test.controllers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.RequestEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * .
 *
 * @author: bcc
 * 2021/10/27
 */
@RestController
@RequestMapping("/http")
public class HttpController {

    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpController.class);

    @GetMapping("/get")
    public Map<String, Object> get(String param1, String param2) {
        Map<String, Object> rs = new HashMap<>();
        rs.put("result", "success");
        LOGGER.info("param1:{},param2:{}", param1, param2);
        return rs;
    }
    @GetMapping("/sleep")
    public Map<String, Object> get(Integer sleep, String config) {
        if (null == sleep) {
            sleep = 3;
        }
        LOGGER.info("start sleep:{},config:{}", sleep, config);
        try {
            Thread.sleep(sleep * 1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Map<String, Object> rs = new HashMap<>();
        rs.put("result", sleep);
        LOGGER.info("finish sleep:{},config:{}", sleep, config);
        return rs;
    }


    @PostMapping("/post")
    public Map<String, Object> post(String param1, String param2) {
        Map<String, Object> rs = new HashMap<>();
        rs.put("result", "success");
        LOGGER.info("param1:{},param2:{}", param1, param2);
        return rs;
    }

    @PostMapping("/post1")
    public Map<String, Object> post1(@RequestBody(required = false) Map<String, Object> param) {
        Map<String, Object> rs = new HashMap<>();
        rs.put("result", "success");
        LOGGER.info("param:{}", param);
        return rs;
    }


    @PostMapping("/post2")
    public Map<String, Object> post2(@RequestBody(required = false)String param, HttpServletRequest request) {
        Map<String, Object> rs = new HashMap<>();
        rs.put("result", "success");
        LOGGER.info("param:{}", param);
        for(String head: Collections.list(request.getHeaderNames())) {
            LOGGER.info("header:{} value:{}", head, request.getHeader(head));
        }
        return rs;
    }

    @PostMapping("/post3")
    public Map<String, Object> post3(@RequestParam("param") String param, HttpServletRequest request) {
        Map<String, Object> rs = new HashMap<>();
        rs.put("result", "success");
        LOGGER.info("param:{}", param);
        for(String head: Collections.list(request.getHeaderNames())) {
            LOGGER.info("================header:{} value:{}================", head, request.getHeader(head));
        }
        return rs;
    }

    @PostMapping("/testRequestEntity")
    public String testRequestEntity(RequestEntity<String> entity){
        //获取请求报文的请求头信息
        HttpHeaders httpHeaders = entity.getHeaders();
        for (String head : httpHeaders.keySet()) {
            LOGGER.info("================header:{} value:{}====================", head, httpHeaders.get(head));
        }
        //)获取请求报文的请求体信息
        String body = entity.getBody();
        LOGGER.info("=======================body:{}", body);
        return "success";
    }


    @GetMapping("test")
    public void test(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
        System.out.println(getParam(request));
    }

    @PostMapping("test2")
    public void test2(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
        System.out.println(getParam2(request));
    }
    /**
     * 获取浏览器参数
     * @param request
     * @return
     */
    private static String getParam(final HttpServletRequest request) throws UnsupportedEncodingException {
        final StringBuilder sb = new StringBuilder();
        final Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            final String name = parameterNames.nextElement();
            sb.append("&");
            sb.append(name);
            sb.append("=");
            final String value = URLEncoder.encode(request.getParameter(name), StandardCharsets.UTF_8.name());
            sb.append(value);
        }
        return sb.toString();
    }


    private static String getParam2(final HttpServletRequest request) throws UnsupportedEncodingException {
        return request.getQueryString();
    }


    @GetMapping("getRequestUrl")
    public String getRequestUrl(final HttpServletRequest request) throws IOException {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    @GetMapping("getRequestUrl2")
    public String getRequestUrl2(final HttpServletRequest request) throws IOException {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI();
    }
}
